<template>
  <div class="app-container">
    <div class="top">
      <el-button
        type="primary"
        @click="show = true"
      >新增</el-button>
    </div>
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
    >
      <el-table-column align="center" label="序号" width="95">
        <template slot-scope="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="箱号" align="center">
        <template slot-scope="scope">
          {{ scope.row.box_number !== null ? scope.row.box_number + "号箱" : "-" }}
        </template>
      </el-table-column>
      <el-table-column label="型号" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.model || "-" }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center">
        <template slot-scope="scope">
          {{ formatterDate(scope.row.create_time) || "-" }}
        </template>
      </el-table-column>
      <el-table-column label="修改时间" align="center">
        <template slot-scope="scope">
          {{ formatterDate(scope.row.update_time) || "-" }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button
            type="primary"
            @click="handleEdit(scope.row)"
          >编辑</el-button>
          <el-button
            type="danger"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="top" style="margin-top:20px">
      <el-pagination
        v-if="total"
        :current-page="params.currentPage"
        :page-sizes="[5, 10, 20, 50]"
        :page-size="params.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="limitchange"
        @current-change="handleCurrentChange"
      />
    </div>
    <el-dialog
      :title="form.id ? '编辑':'添加'"
      :visible.sync="show"
      width="500px"
      :close-on-click-modal="false"
      :before-close="resetFields"
    >
      <el-form ref="ruleForm" :model="form" label-width="120px" :rules="rules" class="pt-20">
        <el-form-item label="请输入箱子号" prop="box_number">
          <el-input v-model="form.box_number" autocomplete="off" />
        </el-form-item>
        <el-form-item label="请输入绑定型号" prop="model">
          <el-input v-model="form.model" autocomplete="off" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resetFields()">取 消</el-button>
        <el-button type="primary" @click="submit">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { delBoxs, updateBoxs, addBox, getBoxsList } from '@/api/table'

export default {
  data() {
    return {
      list: null,
      listLoading: true,
      show: false,
      form: {
        box_number: '', model: '', color: '', num: '', id: null
      },
      rules: {
        box_number: [
          { required: true, message: '请输入箱子号', trigger: 'blur' },
          { pattern: /^\d+$/, message: '请输入整数', trigger: 'blur' }
        ],
        model: [
          { required: true, message: '请输入型号', trigger: 'blur' }
        ]
      },
      params: {
        pageSize: 10,
        currentPage: 1
      },
      total: 0,
      options: []
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 显示分页 当前第几页
    handleCurrentChange(index) {
      if (this.params.currentPage === index) {
        return
      }
      this.params.currentPage = index
      this.getList()
    },
    limitchange(val) {
      this.params.currentPage = 1
      this.params.pageSize = val
      this.getList()
    },
    async submit() {
      await this.$refs['ruleForm'].validate()
      const requestFn = this.form.id ? updateBoxs : addBox
      await requestFn(this.form)
      this.getList()
      this.$message.success(`${this.form.id ? '编辑' : '新增'}成功`)
      this.resetFields()
    },
    async resetFields() {
      await this.$refs['ruleForm'].resetFields()
      this.form = {
        box_number: '', model: '', id: null
      }
      this.show = false
    },
    handleEdit(item) {
      this.form = JSON.parse(JSON.stringify(item))
      this.show = true
    },
    async handleDelete(row) {
      await this.$confirm('确定要删除该号箱吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      await delBoxs({ id: row.id, box_number: row.box_number })
      this.$message.success('删除成功')
      this.list.length === 1 && this.params.currentPage > 1 ? this.params.currentPage -= 1 : ''
      this.getList()
    },
    formatterDate(data) {
      if (!data) return '-'
      const originalDate = new Date(data)
      const formattedDate = originalDate
        .toLocaleString('en-US', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit',
          second: '2-digit',
          hour12: false
        })
        .replace(/,/g, '')
        .replace(/\//g, '-')
      return formattedDate
    },
    async getList() {
      this.listLoading = true
      try {
        const data = await getBoxsList(this.params)
        this.list = data.list
        this.total = data.total
      } finally {
        this.listLoading = false
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.top {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin-bottom: 20px;
}
</style>
